package com.aaa.cars.service.impl;

import com.aaa.cars.dao.CarDao;
import com.aaa.cars.entity.Car;
import com.aaa.cars.service.CarService;
import com.aaa.cars.service.OrderService;
import com.aaa.common.bo.Order;
import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnStatus;
import com.aaa.common.util.ClusterRedisLock;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (Car)表服务实现类
 *
 * @author makejava
 * @since 2020-12-02 21:17:34
 */
@Service("carService")
@Transactional
public class CarServiceImpl implements CarService {
    @Resource
    private CarDao carDao;

    @Autowired
    private ClusterRedisLock clusterRedisLock;

    @Resource
    private OrderService orderService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
//    @Override
//    public synchronized Car queryById(Integer id) {//但应用时，解决多请求的情况下，一个线程执行
    /*public Car queryById(Integer id) {
        //加锁 不存在时写入key
        boolean carSelectOne = clusterRedisLock.lock("carSelectOne", 30);
        Car car = null;
        if(carSelectOne){
            //实际开发循环不要
            *//*for (int i = 0; i < 20; i++) {
                System.out.println("业务正在执行...."+i+","+id);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }*//*

            car = this.carDao.queryById(id);
            //执行完业务，解锁，删除设置的key
            clusterRedisLock.unLock("carSelectOne");
        }
        return car;
    }*/

    @Override
    public Car queryById(Integer id) {
        return carDao.queryById(id);
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param pageNo
     * @param pageSize
     * @param car      实例对象
     * @return 对象列表
     */
    @Override
    public Result queryAll(int pageNo, int pageSize, Car car) {
        if(pageNo==0||pageSize==0){
            throw new CustomException(ExceptionConstant.INVALID_ARGUMENT.getErrorCode(),
                    ExceptionConstant.INVALID_ARGUMENT.getErrorMessage());
        }
        //根据实体获取所有汽车
        List<Car> cars = carDao.queryAll(car);
        //远程调用  获取租出的，或者预约的所有汽车id、开始时间、结束时间方法
        List<Order> orderList =(List<Order>) orderService.queryByTime().getData();
        String string = JSONArray.fromObject(orderList).toString();
        System.out.println("=======================");
        System.out.println(string);
        JSONArray jsonArray = JSONArray.fromObject(string);
        List<Order> list =(List<Order>) JSONArray.toList(jsonArray,Order.class);
        Map<Integer,List<Order>> integerOrderMap=
                list.stream().collect(Collectors.groupingBy(Order::getCarId));
        //获取前端传来的开始时候
        Date startTime = car.getStartTime();
        //获取前端传来的结束时间
        Date endTime = car.getEndTime();
        //判断时间交集
        Iterator<Map.Entry<Integer, List<Order>>> iterator = integerOrderMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<Integer, List<Order>> next = iterator.next();
            Integer key = next.getKey();
            List<Order> value = next.getValue();
            int count=value.size();
            for (Order order : value) {
                if(startTime.getTime()<order.getStartTime().getTime() && endTime.getTime()>order.getStartTime().getTime()
                || startTime.getTime()<order.getEndTime().getTime() && endTime.getTime()>order.getEndTime().getTime()
                || startTime.getTime()>order.getStartTime().getTime() && endTime.getTime()<order.getEndTime().getTime()
                || startTime.getTime()<order.getStartTime().getTime() && endTime.getTime()>order.getEndTime().getTime()){
                    for (Car car1 : cars) {
                        if(car1.getId().equals(key) && car1.getState()!=2 && car1.getState()!=4){
                            car1.setState(3);
                            break;
                        }
                    }
                    count--;
                }else{
                    for (Car car1 : cars) {
                        if(car1.getId()==key && car1.getState()!=2 && car1.getState()!=4 && count==value.size()){
                            car1.setState(1);
                        }
                    }
                }
            }
        }

        //分页
        PageHelper.startPage(pageNo,pageSize);
        PageInfo<Car> carPageInfo = new PageInfo<Car>(cars);
        /*Map tmap = new HashMap();
        //总数量
        tmap.put("total",pageInfo.getTotal());
        //分页数据
        tmap.put("pages",pageInfo.getList());*/
        return new Result(ReturnStatus.SUCCESS.getReturnCode(),
                ReturnStatus.SUCCESS.getReturnMsg(), carPageInfo);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Car> queryAllByLimit(int offset, int limit) {
        return this.carDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param car 实例对象
     * @return 实例对象
     */
    @Override
    public Car insert(Car car) {
        this.carDao.insert(car);
        return car;
    }

    /**
     * 修改数据
     *
     * @param car 实例对象
     * @return 实例对象
     */
    @Override
    public Car update(Car car) {
        int update = this.carDao.update(car);
        System.out.println(update);
        return this.queryById(car.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.carDao.deleteById(id) > 0;
    }
}